<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Api_Standard_Tongyong extends Controller_Pc_Api_Base
{

    public function before()
    {
        parent::before();
    }

    //通用首页数据
    public function action_list()
    {
        $typeid = Common::remove_xss($this->request_body->content->typeid);//扩展产品id
        $destpy = Common::remove_xss($this->request_body->content->destpy);//目的地拼音
        $sorttype = Common::remove_xss($this->request_body->content->sorttype);//排序方式
        $attrid = Common::remove_xss($this->request_body->content->attrid);//筛选id
        $keyword = Common::remove_xss($this->request_body->content->keyword);//关键词
        $page = Common::remove_xss($this->request_body->content->page);//页数
        $page = empty($page) ? 1 : $page;
        $pagesize = 10;
        $offset = $pagesize * ($page - 1);
        $where = ' WHERE a.ishidden=0 and a.typeid=' . $typeid . ' ';

        if (!empty($destpy)) {
            $destid = DB::select('id')->from('destinations')->where('pinyin', '=', $destpy)->execute()->get('id');
        }

        //排序
        $orderBy = "";
        if (!empty($sorttype)) {
            if ($sorttype == 1)//价格升序
            {
                $orderBy = "  --a.price ASC,";
            } else if ($sorttype == 2) //价格降序
            {
                $orderBy = "  --a.price DESC,";
            } else if ($sorttype == 3) //销量降序
            {
                $orderBy = " a.bookcount DESC,";
            } else if ($sorttype == 4)//推荐
            {
                $orderBy = " a.bookcount DESC,";
            }
        }

        //关键词
        if (!empty($keyword)) {
            $where .= " AND a.title like '%$keyword%' ";
        }
        //按属性
        if (!empty($attrid)) {
            $where .= Product::get_attr_where($attrid);
        }
        if (!empty($destid)) {
            $where .= " AND FIND_IN_SET($destid,a.kindlist) ";
        }
        //如果选择了目的地
        if (!empty($destid)) {
            $sql = "SELECT a.* FROM `sline_model_archive` a ";
            $sql .= "LEFT JOIN `sline_kindorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=$typeid AND b.classid=$destid)";
            $sql .= $where;
            $sql .= "ORDER BY IFNULL(b.displayorder,9999) ASC,{$orderBy}a.modtime DESC,a.addtime DESC ";

        } else {
            $sql = "SELECT a.* FROM `sline_model_archive` a ";
            $sql .= "LEFT JOIN `sline_allorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=$typeid )";
            $sql .= $where;
            $sql .= "ORDER BY IFNULL(b.displayorder,9999) ASC,{$orderBy}a.modtime DESC,a.addtime DESC ";

        }

        //计算总数
        $totalSql = "SELECT count(*) as num " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by

        $totalNum = DB::query(Database::SELECT, $totalSql)->execute()->get('num');

        $sql .= "LIMIT {$offset},{$pagesize}";

        $arr = DB::query(1, $sql)->execute()->as_array();

        $model_info = ORM::factory('model', $typeid);
        foreach ($arr as &$v) {
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], $typeid); //评论次数
            $v['sellnum'] = Model_Member_Order::get_sell_num($v['id'], $typeid) + $v['bookcount']; //销售数量
            $v['score'] = $v['satisfyscore'] . '%';
            $v['price'] = Model_Tongyong::get_minprice($v['id'], array('info' => $v));//最低价
            $v['attrlist'] = Model_Model_Attr::get_attr_list($v['attrid'], $typeid);//属性列表.
            $v['url'] = Common::get_web_url($v['webid']) . "/{$model_info->pinyin}/show_{$v['aid']}.html";
            $v['iconlist'] = Product::get_ico_list($v['iconlist']);
            $v['litpic'] = Common::img($v['litpic'], 220, 150);
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr
        );
        $this->send_datagrams($this->client_info['id'], $out, $this->client_info['secret_key']);
    }

    //通用详细页
    public function action_show()
    {
        $webid = Common::remove_xss($this->request_body->content->webid);//站点id
        $webid = $webid ? $webid : 0;
        $aid = Common::remove_xss($this->request_body->content->aid);//前台访问id
        $typeid = Common::remove_xss($this->request_body->content->typeid);//模型id
        $id = Common::remove_xss($this->request_body->content->productid);
        $info = Model_Tongyong::detail($aid, $typeid, $webid,$id);
        //兼容只传productid
        $typeid = $info['typeid'];
        $aid = $info['aid'];
        $mid = Common::remove_xss($this->request_body->content->mid);//会员id
        if (!$info) {
            $this->send_datagrams($this->client_info['id'], array(), $this->client_info['secret_key']);
        }
        //seo
        $seoInfo = Product::seo($info);
        //产品图片
        $info['piclist'] = Product::pic_list($info['piclist']);
        $p = array();
        foreach ($info['piclist'] as &$pic) {
            $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
            array_push($p, $pi);
        }
        $info['piclist'] = $p;
        //属性列表
        $info['attrlist'] = Model_Tongyong::product_attr($info['attrid'], $typeid);
        //最低价
        $info['price'] = Model_Tongyong::get_minprice($info['id'], array('info' => $info));
        //市场价
        $info['sellprice'] = Model_Tongyong::get_min_sellprice($info['id']);
        //满意度
        $info['score'] = St_Functions::get_satisfy($typeid, $info['id'], $info['satisfyscore']);
        //$info['satisfyscore'] = St_Functions::get_satisfy($typeid, $info['id'], $info['satisfyscore']);
        //点评数
        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], $typeid);
        //销售数量
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], $typeid) + $info['bookcount'];
        //产品编号
        $info['series'] = Product::product_number($info['id'], $typeid);
        //产品图标
        $info['iconlist'] = Product::get_ico_list($info['iconlist']);

        //供应商
        $info['suppliers'] = null;
        if ($info['supplierlist']) {
            $info['suppliers'] = DB::query(1, "SELECT suppliername FROM `sline_supplier` WHERE id={$info['supplierlist']}")->execute()->current();
        }

        $info['content'] = Product::strip_style($info['content']);
        //支付方式

        $info['jifentprice_info'] = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], $typeid);
        $info['jifenbook_info'] = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], $typeid);
        $info['jifencomment_info'] = Model_Jifen::get_used_jifencomment($typeid);

        //分销赚取的金额
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            if (!empty($mid)) {
                $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid", '=', $mid)->execute()->current();
                $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_' . $typeid, $fxgroupid['fxgroupid']);
                if ($commission_type == 1) {
                    $commission_rate = Model_Fenxiao::get_commission_rate($typeid, $info['id'], $fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_rate[0] * 100;
                    $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                    $v['commission'] .= '%';
                    $v['profit'] = $info['price'] * $commission_rate[0];
                } else if ($commission_type == 2) {
                    $commission_rate = Model_Fenxiao::get_commission_rate_platform($typeid, $info['id'], $fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_rate[0] * 100;
                    $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                    $v['commission'] .= '%';
                    $temp_order = array('typeid' => $typeid, 'productautoid' => $info['id'], 'totalprice' => $info['price'], 'dingnum' => 1);
                    $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                    $platform_price = $platform_price == 0 ? $info['price'] : $platform_price;
                    $v['profit'] = $platform_price * $commission_rate[0];
                } else {
                    $commission_cash = Model_Fenxiao::get_commission_cash_line($typeid, $info['id'], $fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_cash[0]['adult'];
                    $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                    $v['profit'] = $v['commission'];
                }
                $info['profit'] = $v['profit'];
            }
        }

        // 更加ID查询可用的优惠券
        if (St_Functions::is_normal_app_install('coupon')) {
            $info['coupon_list'] = Model_Coupon::get_product_coupon_list($info['id'], $typeid);
            // 处理个人优惠券
            $cdata=array();
            foreach ($info['coupon_list'] as $key=>$v)
            {
                $receive_status = Model_Api_Standard_Coupon::check_receive_status($v['id'],$mid,$v['totalnumber'],$v['maxnumber']);
                if($receive_status['status']==1){
                    array_push($cdata,$v);
                }
            }
            $info['coupon_list']=$cdata;
        }
        //扩展字段信息
        $extend_info = Model_Tongyong::extend($info['id'], $typeid);
        $minsuit = $this->getMinSuit($info['id']);//套餐情况

        //介绍
        $params = array(
            'typeid' => $typeid,
            'productinfo' => $info,
            'onlyrealfield' => 1,
            'pc' => 0,

        );
        $info['detail_list'] = self::get_content($params);


        $trueresult = array(
            'minsuit' => $minsuit,
            'seoinfo' => $seoInfo,
            'info' => $info,
            'extendinfo' => $extend_info
        );
        $this->send_datagrams($this->client_info['id'], $trueresult, $this->client_info['secret_key']);
    }

    public function getMinSuit($id)
    {
        $suitModel = ORM::factory('model_suit')->where('productid', '=', $id)->order_by('ourprice', 'asc')->get_all();
//        if (!$suitModel->loaded())
//            return null;
        return $suitModel;
    }

    //立即预定
    public function action_book()
    {
        $mid = Common::remove_xss($this->request_body->content->mid);//用户id
        $id = Common::remove_xss($this->request_body->content->id);//产品id
        $typeid = Common::remove_xss($this->request_body->content->typeid);//模型id
        $suitid = Common::remove_xss($this->request_body->content->suitid);//套餐id
        //检测是否为有效用户
        if (!empty($mid)) {
            $sql = "SELECT mid FROM sline_member WHERE mid='{$mid}' LIMIT 1";
            $ar = DB::query(Database::SELECT, $sql)->execute()->as_array();
            if (!$ar) {
                $this->send_datagrams($this->client_info['id'], array(), $this->client_info['secret_key']);
            }
        } else {
            $this->send_datagrams($this->client_info['id'], array(), $this->client_info['secret_key']);
        }
        $id = intval($id);
        $model = ORM::factory('model_archive', $id);
        if (!$model->loaded()) {
            $this->send_datagrams($this->client_info['id'], array(), $this->client_info['secret_key']);
        }
        $info = $model->as_array();
        $info['bookNumber'] = 0;
        $jifentprice_info = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], $typeid);
        $member = Model_Member::get_member_byid($mid);
        //查询默认地址
        $defaultaddr=DB::select()->from('member_address')
            ->where('memberid', '=',$mid)
            ->and_where('is_default','=',1)
            ->execute()
            ->current();
        $result = array(
            'jifentprice_info' => $jifentprice_info,
            'member' => $member,
            'info' => $info,
            'userinfo' => $member,
            'suitid' => $suitid,
            'defaultaddr'=>$defaultaddr
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //订单创建
    public function action_create()
    {
        //套餐id
        $suitid = Common::remove_xss($this->request_body->content->suitid);
        //联系人
        $linkman = Common::remove_xss($this->request_body->content->linkman);
        //手机号
        $linktel = Common::remove_xss($this->request_body->content->linktel);
        $linkidcard = Common::remove_xss($this->request_body->content->linkidcard);
        //备注信息
        $remark = Common::remove_xss($this->request_body->content->remark);
        //产品id
        $id = Common::remove_xss($this->request_body->content->productid);
        //使用时间
        $usedate = Common::remove_xss($this->request_body->content->usedate);
        //预订数量
        $dingnum = Common::remove_xss($this->request_body->content->dingnum);

        $needJifen = Common::remove_xss($this->request_body->content->needjifen);

        $typeid = Common::remove_xss($this->request_body->content->typeid);
        $mid = Common::remove_xss($this->request_body->content->mid);
        Common::session('member', array('mid' => $mid));
        $address = Common::remove_xss($this->request_body->content->address);

        $couponid = Common::remove_xss($this->request_body->content->couponid);

        $info = ORM::factory('model_archive')->where("id=$id")->find()->as_array();

        $suitArr = ORM::factory('model_suit')
            ->where("id=:suitid")
            ->param(':suitid', $suitid)
            ->find()
            ->as_array();

        $suitArr['dingjin'] = Currency_Tool::price($suitArr['dingjin']);
        $suitArr['ourprice'] = Currency_Tool::price($suitArr['ourprice']);

        $price_info = DB::select()->from('model_suit_price')
            ->and_where('suitid', '=', $suitid)
            ->and_where('day', '=', strtotime($usedate))->execute()->current();
        $price_info['price'] = Currency_Tool::price($price_info['price']);
        if (!Model_Tongyong::check_storage($id, intval($dingnum), $suitid, $usedate)) {
            $result = array(
                'status' => false,
                'msg' => '库存不足'
            );
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }
        if ($suitArr['paytype'] == '3')//这里补充一个当为二次确认时,修改订单为未处理状态.
        {
            $info['need_confirm'] = 1;
            $info['status'] = 0;

        } else {
            $info['need_confirm'] = 0;
            $info['status'] = 1;

        }

        $info['name'] = $info['title'] . "({$suitArr['suitname']})";

        $info['paytype'] = $suitArr['paytype'];

        $info['dingjin'] = doubleval($suitArr['dingjin']);


        $info['ourprice'] = doubleval($price_info['price']);

        $info['childprice'] = 0;

        $info['usedate'] = $usedate;

        $ordersn = Product::get_ordersn($typeid);
        $userInfo = Model_Member::get_member_byid($mid);
        $jifentprice = 0;
        $useJifen = 0;
        if ($needJifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], $typeid, $needJifen, $userInfo);
            $useJifen = empty($jifentprice) ? 0 : 1;
            $needJifen = empty($jifentprice) ? 0 : $needJifen;
        }
        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment($typeid);
        $jifencomment = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

        //自动关闭订单时间
        $auto_close_time = $suitArr['auto_close_time'] ? $suitArr['auto_close_time'] : 0;
        if ($auto_close_time) {
            $auto_close_time = time() + $auto_close_time;
        }
        $arr = array(

            'ordersn' => $ordersn,

            'webid' => 0,

            'typeid' => $typeid,

            'productautoid' => $id,

            'productaid' => $info['aid'],

            'productname' => $info['name'],

            'litpic' => $info['litpic'],

            'price' => $info['ourprice'],

            'childprice' => $info['childprice'],

            'jifentprice' => $jifentprice,
            'jifenbook' => $info['jifenbook_id'],
            'jifencomment' => $jifencomment,

            'paytype' => intval($info['paytype']),

            'dingjin' => $info['dingjin'],

            'usedate' => $info['usedate'],

            'departdate' => '',

            'addtime' => time(),

            'memberid' => $userInfo['mid'],

            'dingnum' => $dingnum,

            'childnum' => 0,

            'oldprice' => 0,

            'oldnum' => 0,

            'linkman' => $linkman,

            'linktel' => $linktel,

            'linkidcard' => $linkidcard,

            'suitid' => $suitid,

            'remark' => $remark,

            'status' => $info['status'] ? $info['status'] : 0,

            'usejifen' => $useJifen,
            'needjifen' => $needJifen,
            'receiver_address_id' => $address ? (int)$address : 0,
            'refund_restriction' => $suitArr['refund_restriction'],//退改条件
            'auto_close_time' => $auto_close_time, //自动关闭订单时间
            'need_confirm' => $info['need_confirm']

        );

        /*--------------------------------------------------------------优惠券信息------------------------------------------------------------*/
        //优惠券判断
        $croleid = intval($couponid);
        if ($croleid) {
            $cid = DB::select('cid')->from('member_coupon')->where("id=$croleid")->execute()->current();
            $totalprice = Model_Coupon::get_order_totalprice($arr);
            $ischeck = Model_Coupon::check_samount($croleid, $totalprice, $typeid, $info['id'], $usedate);
            if ($ischeck['status'] == 1) {
                Model_Coupon::add_coupon_order($cid, $ordersn, $totalprice, $ischeck, $croleid); //添加订单优惠券信息
            } else {
                $result = array(
                    'status' => false,
                    'msg' => '优惠券无效'
                );
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
        }
        /*-----------------------------------------------------------------优惠券信息--------------------------------------*/

        //添加订单

        if (ST_Product::add_order($arr, 'Model_Model_Archive', $arr)) {
            //地址信息保存
//            $user = DB::select('*')->from('member')->where('mobile', '=', $linktel)->execute()->current();
//            $use_address=Common::remove_xss($this->request_body->content->use_address);
//            $use_address=intval($use_address) ? intval($use_address) : 0;
//            $province=Common::remove_xss($this->request_body->content->province);
//            $city=Common::remove_xss($this->request_body->content->city);
//            $phone=Common::remove_xss($this->request_body->content->phone);
//            $postcode=Common::remove_xss($this->request_body->content->postcode);
//            $receiver=Common::remove_xss($this->request_body->content->receiver);
//            $is_default=Common::remove_xss($this->request_body->content->is_default);
//            if($user&&$use_address==1)
//            {
//                $data = array(
//                    'memberid' => $user['mid'],
//                    'province' => $province,
//                    'city' => $city,
//                    'address' => $address,
//                    'phone' => $phone,
//                    'postcode' => $postcode,
//                    'receiver' => $receiver,
//                    'is_default' => intval($is_default) ? intval($is_default) : 0
//                );
//                list($address_id, $flag) = DB::insert('member_address', array_keys($data))->values(array_values($data))->execute();
//                //是否将当前地址设置为默认地址
//                if ($flag && $data['is_default'])
//                {
//                    DB::update('member_address')->set(array('is_default' => 0))->where('memberid', '=', $user['mid'])->and_where('id', '!=', $address_id)->execute();
//                }
//                //将当前地址信息更新至订单信息中
//                DB::update('member_order')->set(array('receiver_address_id' => $address_id))->where('memberid', '=', $user['mid'])->and_where('ordersn', '=', $ordersn)->execute();
//            }

            $orderInfo = Model_Member_Order::order_info($ordersn);
            //返回订单号
            $result = array(
                'status' => true,
                'orderInfo' => $orderInfo
            );
            St_Product::event($ordersn);
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }
    }

    //当前套餐价格
    public function action_ajax_current_suit()
    {
        $suitid = Common::remove_xss($this->request_body->content->suitid);//套餐id
        $use_date = Common::remove_xss($this->request_body->content->usedate);//使用时间
        $productid = Common::remove_xss($this->request_body->content->productid);//产品id
        $list = Model_Tongyong::current_suit_price($productid, $suitid, $use_date);
        if (empty($list)) {
            $this->send_datagrams($this->client_info['id'], array(), $this->client_info['secret_key'], false, '未找到价格信息');
        } else {
            //获得套餐信息
            $suitdetail = DB::select()->from('model_suit')
                ->where('productid', '=', $productid)
                ->and_where('id', '=', $suitid)
                ->execute()->current();
            $list['suitdetail'] = $suitdetail;
            $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
        }
    }

    //检测库存
    public function action_ajax_check_stock()
    {
        $productid = Common::remove_xss($this->request_body->content->productid);//产品id
        $userdate = Common::remove_xss($this->request_body->content->userdate);//使用时间
        $suitid = Common::remove_xss($this->request_body->content->suitid);//套餐id
        if ($productid || $userdate || $suitid) {
            $this->send_datagrams($this->client_info['id'], ['number' => 0], $this->client_info['secret_key']);
        }
        $data = DB::select()->from('model_suit_price')->where('productid', '=', intval($productid))->and_where('day', '=', strtotime($userdate))->and_where('suitid', '=', $suitid)->execute()->current();
        if ($data) {
            $this->send_datagrams($this->client_info['id'], ['number' => $data['number']], $this->client_info['secret_key']);
        } else {
            $this->send_datagrams($this->client_info['id'], ['number' => 0], $this->client_info['secret_key']);
        }
    }

    //获得目的地
    public function action_destylist()
    {
        $destpy = Common::remove_xss($this->request_body->content->destpy);
        $typeid = Common::remove_xss($this->request_body->content->typeid);
        $isparent = Common::remove_xss($this->request_body->content->isparent);
        $destpy = empty($destpy) ? 'all' : $destpy;
        $dest_info = array('id' => '0', 'kindname' => '目的地', 'pinyin' => 'all');
        $pid = 0;
        if ($destpy != 'all') {
            $dest_info = DB::select()->from('destinations')->where('pinyin', '=', $destpy)->execute()->current();
            $subnum = DB::select(array(DB::expr("count(*)"), 'num'))->from('destinations')->where('pid', '=', $dest_info['id'])->and_where('isopen', '=', 1)->and_where(DB::expr("FIND_IN_SET({$typeid},opentypeids)"), '>', 0)->execute()->get('num');
            $pid = $isparent == 1 || $subnum <= 0 ? $dest_info['pid'] : $dest_info['id'];
        }
        $parents = null;
        if ($pid != 0) {
            $parents = Model_Destinations::get_parents($pid);
            $parents = array_reverse($parents);
            $parents[] = $dest_info;
        }
        $list = DB::select('id', 'pinyin', 'kindname')->from('destinations')->where('isopen', '=', 1)->and_where('pid', '=', $pid)->and_where(DB::expr("FIND_IN_SET({$typeid},opentypeids)"), '>', 0)->execute()->as_array();
        foreach ($list as &$child) {
            $child['subnum'] = DB::select(array(DB::expr("count(*)"), 'num'))->from('destinations')->where('pid', '=', $child['id'])->and_where('isopen', '=', 1)->and_where(DB::expr("FIND_IN_SET({$typeid},opentypeids)"), '>', 0)->execute()->get('num');
        }
        $parent = DB::select('id', 'kindname', 'pinyin')->from('destinations')->where('id', '=', $pid)->execute()->current();
        $result = array(
            'list' => $list,
            'parents' => $parents,
            'parent' => $parent
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //获得产品属性
    public function action_getattr()
    {
        $typeid = Common::remove_xss($this->request_body->content->typeid);//扩展产品id
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            ),

            'attribute' => array(),

        );
        //属性
        $result['attribute'] = DB::select('id', array('attrname', 'name'))->from('model_attr')->where('pid', '=', 0)->and_where('isopen', '=', 1)->and_where('typeid', '=', $typeid)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
        foreach ($result['attribute'] as &$item) {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('model_attr')->where('pid', '=', $item['id'])->and_where('isopen', '=', 1)->and_where('typeid', '=', $typeid)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();

        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 套餐列表
     */
    public function action_current_suit_list()
    {
        $id = intval($this->request_body->content->id);

        $suits = DB::select()->from('model_suit')->where('productid', '=', $id)->execute()->as_array();
        $result = array();
        $selected_suit_id = 0;
        foreach ($suits as &$suit) {
            $selected_suit_id = $selected_suit_id == 0 ? $suit['id'] : $selected_suit_id;
            $express_template = DB::select()->from('express_template')->where('id', '=', $suit['freightid'])->execute()->current();
            $min_price = 0;
            if (!empty($express_template)) {
                $express_template['plan_list'] = Model_Express_Plan::get_template_planlist($suit['freightid']);
                foreach ($express_template['plan_list'] as $plan) {
                    $min_price = $min_price == 0 || ($min_price > $plan['start_price'] && $plan['start_price'] > 0) ? $plan['start_price'] : $min_price;
                }
            }
            $express_template['min_price'] = Currency_Tool::price($min_price);
            $suit['express_template'] = $express_template;
            //$list = Model_Tongyong::current_suit_price($id, $suit['id'], date('Y-m-d', time()));
            $arr = DB::select()->from('model_suit_price')->where('productid', '=', $id)->and_where('suitid', '=', $suit['id'])
                ->and_where('day', '=', strtotime(date('Y-m-d', time())))->and_where('number', '!=', 0)->execute()->current();
            $data = !empty($arr) ? $arr : array();
            $list=$data;
            if (!empty($list)) {
                $suit['price'] = $list['price'];
            } else {
                $suit['price'] = 0;
            }
            //$suit['price'] = Currency_Tool::price($suit['price']);
            $suit['description'] = Model_Api_Standard_Xcx::filter_content($suit['description']);

            $result[$suit['id']] = $suit;
        }
        $this->send_datagrams($this->client_info['id'], array('suit_list' => $result, 'selected_suit_id' => $selected_suit_id), $this->client_info['secret_key']);
    }

    //通用介绍
    public static function get_content($params)
    {
        $default = array(
            'typeid' => $params['typeid'],
            'productinfo' => $params['productinfo'],
            'onlyrealfield' => 1,
            'pc' => 0

        );

        $params = array_merge($default, $params);
        extract($params);

        $isExists = DB::select()->from('model')->where("id={$params['typeid']}")->execute()->current();
        if (empty($isExists)) {
            return '';
        }
        $table = 'sline_model_content';
        $extend_tables = "sline_{$isExists['addtable']}";


        $sql = "SELECT columnname,chinesename,isrealfield FROM {$table} ";

        $sql .= "WHERE webid=0 and isopen=1 and typeid=" . $params['typeid'];

        $sql .= " ORDER BY displayorder ASC";
        $arr = DB::query(1, $sql)->execute()->as_array();

        //扩展表数据
        $productid = $params['productinfo']['id'];//产品id
        $sql = "SELECT * FROM $extend_tables WHERE productid='$productid'";
        $ar = DB::query(1, $sql)->execute()->as_array();
        $list = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian') {
                continue;
            }
            $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
            $content = $content ? $content : '';

            if (empty($content)) continue;

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] = Model_Api_Standard_Xcx::filter_content($content);
            $list[] = $a;

        }
        return $list;

    }

    //订单详情
    public function action_order_info()
    {
        $id = $this->request_body->content->id;
        $userid = intval($this->request_body->content->userid);
        $ordersn = DB::select('ordersn')->from('member_order')->where('id','=',$id)->execute()->get('ordersn');
        $row = Model_Member_Order::order_info($ordersn, $userid);

        if(empty($row)){
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'订单不存在'), $this->client_info['secret_key']);
            return;
        }
        //分割订单产品名称
        $tempArr = array_filter(preg_split('`[\(\)]`', $row['productname']));
        $row['subname'] = count($tempArr) > 1 ? $tempArr[count($tempArr) - 1] : '';
        $row['productname'] = str_replace("({$row['subname']})", '', $row['productname']);

        $num = array();
        if ($row['dingnum'] > 0)
        {
            array_push($num, "{$row['dingnum']}个");
        }

        $row['num'] = implode('，', $num);
        //评论
        //封面图

        //$product_info = ORM::factory('techan',$row['productautoid'])->as_array();
        $product_info = Model_Tongyong::detail_id($row['productautoid']);
        $row['litpic'] = Common::img($product_info['litpic']);

//        $status=DB::select()->from('techan_order_status')->where('status','=',$row['status'])->and_where('is_show','=',1)->execute()->current();
//        $row['statusname']=$status['status_name'];
        $status=DB::select()->from('tongyong_order_status')
            ->where('is_show', '=', 1)
            ->and_where('status','=',$row['status'])
            ->execute()->current();
        $row['statusname']=$status['status_name'];

        if($row['receiver_address_id'])
        {
            $receiver_address = DB::select()->from('member_address')->where('id','=',$row['receiver_address_id'])->execute()->current();
            $row['receiver_address'] =  $receiver_address;

        }
        $row = Pay_Online_Refund::get_refund_info($row);
        $express = DB::select()->from('express_company')->where('pinyin','=',$row['express_company'])->execute()->current();

        $suit = Model_Tongyong::suit_info($row['suitid']);
        $suit['express_template'] = DB::select()->from('express_template')->where('id','=',$suit['freightid'])->execute()->current();
        $row['suit'] = $suit;
        $row['express'] = $express;

        $row['addtime_fmt'] = date('Y-m-d H:i:s',$row['addtime']);
        $row["web_url"] =  $GLOBALS['cfg_basehost'];
        $this->send_datagrams($this->client_info['id'], $row, $this->client_info['secret_key']);
    }

    //确认收货
    public function action_xcx_order_express_confirm()
    {
        $ordersn =$this->request_body->content->ordersn;
        $userid = intval($this->request_body->content->userid);

        $model = ORM::factory('member_order')->where('ordersn','=',$ordersn)->and_where('memberid','=',$userid)->find();

        if(!$model->loaded() || $model->status!='8' || $model->typeid!='118')
        {
            $result = array('status' => false, 'message' => __('错误'));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            return;
        }

        $model->status = 5;
        $model->save();
        if($model->saved())
        {
            $model->reload();
            $info = $model->as_array();
            Model_Member_Order::back_order_status_changed(8, $info, 'Model_Techan');
            $result=array('status' => true, 'message' => __('已完成'));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

    }

    /**
     * 通用详情
     */
    public function action_detail()
    {
        $params['id'] = intval($this->request_body->content->productid);
        $params['userid'] = intval($this->request_body->content->userid);
        if($params['id'])
        {
            if($params['id'])
            {
                $id = $params['id'];
                $userid = $params['userid'];
                $info = DB::select()->from('model_archive')->where('id','=',$id)->execute()->current();
                //seo
                $seo_info = Product::seo($info);

                $info['seo_info'] = $seo_info;
                //产品图片
                $piclist = Product::pic_list($info['piclist']);
                $p = array();
                foreach($piclist as &$pic)
                {
                    $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
                    array_push($p,$pi);
                }
                $info['piclist'] = $p;
                //属性列表
                $info['attrlist'] = Model_Tongyong::product_attr($info['attrid'], $info['typeid']);
                //最低价
                $info['price'] = Model_Tongyong::get_minprice($info['id'], array('info' => $info));
                //市场价
                $info['sellprice'] = Model_Tongyong::get_min_sellprice($info['id']);
                //满意度
                $info['score'] = St_Functions::get_satisfy($info['typeid'], $info['id'], $info['satisfyscore']);
                //$info['satisfyscore'] = St_Functions::get_satisfy($typeid, $info['id'], $info['satisfyscore']);
                //点评数
                $info['commentnum'] = Model_Comment::get_comment_num($info['id'], $info['typeid']);
                //销售数量
                $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], $info['typeid']) + $info['bookcount'];
                //产品编号
                $info['series'] = Product::product_number($info['id'], $info['typeid']);
                //产品图标
                $info['iconlist'] = Product::get_ico_list($info['iconlist']);
                //行程附件
                $info['linedoc'] = unserialize($info['linedoc']);

                $info['linedoc_path'] = empty($info['linedoc']['path']) ? '' : Model_Api_Standard_System::reorganized_resource_url($info['linedoc']['path'][0]);
                //满意度
                $info['score'] = St_Functions::get_satisfy($info['typeid'], $info['id'], $info['satisfyscore']);

                $info['litpic'] = Model_Api_Standard_System::reorganized_resource_url($info['litpic']);

                $info['basehost'] = $GLOBALS['cfg_basehost'];

                $info['jieshao'] = Model_Api_Standard_Xcx::filter_content($info['jieshao']);

                // 处理视频
                if($info['product_video'])
                {
                    $product_video = explode('|',$info['product_video']);
                    $info['product_video'] = isset($product_video[0])? Model_Api_Standard_System::reorganized_resource_url($product_video[0]):'';
                }

                //扩展字段信息
                $extend_info = Model_Tongyong::extend($info['id'], $info['typeid']);
                $info['extend_info'] = $extend_info;

                //套餐信息
                $info['suit_info'] = $this->getMinSuit($info['id']);//套餐情况

                //线路详情内容
                $params = array(
                    'typeid' => $info['typeid'],
                    'productinfo' => $info,
                    'onlyrealfield' => 1,
                    'pc' => 0
                );
                $info['detail_list'] = self::get_content($params);
                //分销赚取的金额
                if(St_Functions::is_normal_app_install('mobiledistribution'))
                {
                    if(!empty($userid))
                    {
                        $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                        $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$params['typeid'],$fxgroupid['fxgroupid']);
                        if($commission_type==1)
                        {
                            $commission_rate = Model_Fenxiao::get_commission_rate($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                            $v['commission'] =$commission_rate[0]*100;
                            $v['commission'] = empty($v['commission'])?0:$v['commission'];
                            $v['commission'] .='%';
                            $v['profit'] = $info['price']*$commission_rate[0];
                        }
                        else if($commission_type==2)
                        {
                            $commission_rate = Model_Fenxiao::get_commission_rate_platform($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                            $v['commission'] =$commission_rate[0]*100;
                            $v['commission'] = empty($v['commission'])?0:$v['commission'];
                            $v['commission'] .='%';
                            $temp_order = array('typeid'=>$params['typeid'],'productautoid'=>$info['id'],'totalprice'=>$info['price'],'dingnum'=>1);
                            $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                            $platform_price = $platform_price==0? $info['price']:$platform_price;
                            $v['profit'] = $platform_price*$commission_rate[0];
                        }
                        else
                        {
                            $commission_cash = Model_Fenxiao::get_commission_cash_line($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                            $v['commission'] = $commission_cash[0]['adult'];
                            $v['commission'] = empty($v['commission'])?0:$v['commission'];
                            $v['profit'] = $v['commission'];
                        }
                        $info['profit'] = $v['profit'];
                    }
                }
                //拼团
                $info['together'] = '';
                if(St_Functions::is_normal_app_install('together'))
                {
                    $info['together'] = Model_Together::get_product_show_list(1,$info['id']);
                    $planlist = Model_Together::get_add_product_list(1,$info['id']);
                    $together_list = Model_Together::together_join_list(1,$info['id'],2,$planlist);
                    foreach ($together_list as &$t)
                    {
                        $t['member']['litpic'] = Model_Api_Standard_System::reorganized_resource_url($t['member']['litpic']);
                    }
                    $info['together_list'] = $together_list;
                }
                //$info['near_price_days'] = self::_get_near_price_days($info);
            }
            else
            {
                $info= array();
            }

            if (empty($info))
            {
                $this->send_datagrams($this->client_info['id'], $info, $this->client_info['secret_key'], false, '查询失败', '查询失败');
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], $info, $this->client_info['secret_key']);
            }
        }
    }


}